package org.example.types.aop;

/**
 * @author lxc18
 * @date 2025/4/8 11:16
 * @description RateLimitAspect
 */

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.example.types.annotation.RateLimit;
import org.example.types.exception.RateLimitExceededException;
import org.example.types.util.RedisRateLimiter;
import org.springframework.stereotype.Component;

@Aspect
@Component
@RequiredArgsConstructor
@Slf4j
public class RateLimitAspect {

    private final RedisRateLimiter rateLimiter;

    @Around("@annotation(rateLimit)")
    public Object around(ProceedingJoinPoint joinPoint, RateLimit rateLimit) throws Throwable {
        String key = rateLimit.key();
        int limit = rateLimit.limit();
        int windowSize = rateLimit.windowSize();
//        log.info("[RateLimit] 触发限流，key：{}，limit：{}", key, limit);
        boolean allowed = rateLimiter.tryAcquire(key, limit,windowSize);
        if (!allowed) {
            throw new RateLimitExceededException(limit, windowSize);
        }

        return joinPoint.proceed();
    }
}
